from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from dify.api import run_workflow, parse_workflow_response1
from dify.models import Report
from .serializers import (
    IndustryReportSerializer,
    IndustryReportCreateSerializer,
    IndustryReportListSerializer,
    IndustryReportUpdateSerializer
)
from rest_framework.permissions import IsAuthenticated
import re
from django.http import HttpResponse

class CustomPagination(PageNumberPagination):
    """自定义分页器"""
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 100

def process_report_content(content):
    """处理报告内容：移除markdown标记和多余空格"""
    # 移除 markdown 标记
    content = re.sub(r'#+\s*', '', content)  # 移除标题标记
    content = re.sub(r'\*\*', '', content)   # 移除加粗标记
    
    # 处理多余的空格和空行
    lines = content.split('\n')
    processed_lines = []
    
    for line in lines:
        # 跳过空行
        if not line.strip():
            continue
        # 处理每行内容
        processed_line = ' '.join(line.split())  # 移除多余空格
        processed_lines.append(processed_line)
    
    # 使用单个换行符连接所有行
    return '\n'.join(processed_lines)

class IndustryReportViewSet(viewsets.ModelViewSet):
    """
    产业报告视图集
    提供以下接口：
    - GET /api/v1/industry/ - 获取报告列表
    - GET /api/v1/industry/{id}/ - 获取单个报告
    - POST /api/v1/industry/generate/ - 生成新报告
    - DELETE /api/v1/industry/{id}/ - 删除报告
    """
    serializer_class = IndustryReportSerializer
    pagination_class = CustomPagination
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'list':
            return IndustryReportListSerializer
        elif self.action == 'update' or self.action == 'partial_update':
            return IndustryReportUpdateSerializer
        return self.serializer_class

    def get_queryset(self):
        """获取当前用户的产业报告列表"""
        base_queryset = Report.objects.filter(workflow_name=2)  # 2表示产业报告
        if self.request.user.is_superuser:
            return base_queryset  # 超级管理员可以看到所有产业报告
        return base_queryset.filter(user=self.request.user)  # 普通用户只能看到自己的

    def list(self, request, *args, **kwargs):
        """获取报告列表"""
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        print("abc")
        if not page:
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'count': 0,
                    'next': None,
                    'previous': None,
                    'results': [],
                    'empty_tip': '当前列表为空'
                }
            })
            
        serializer = self.get_serializer(page, many=True)
        response = self.get_paginated_response(serializer.data)
        
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': response.data
        })

    @action(detail=False, methods=['post'])
    def generate(self, request):
        """生成新报告"""
        try:
            keyword = request.data.get('keyword')
            if not keyword:
                return Response({
                    'code': 400,
                    'message': '关键词不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 调用Dify API生成报告
            response = run_workflow(
                workflow_name="产业报告",
                inputs={"context": keyword},
                user=str(request.user.id)
            )
            print("Dify res:", response)
            # 处理内容，移除markdown标记和多余空格
            content = process_report_content(parse_workflow_response1(response))
            
            # 从内容中提取标题（现在内容已经没有###标记了）
            title = f"{keyword}产业报告"
            ##lines = content.split('\n')
            ##if lines:
            ##    title = lines[0]  # 使用第一行作为标题
            
            # 创建报告
            report = Report.objects.create(
                title=title,
                content=content,
                workflow_name=2,  # 2表示产业报告
                industry=keyword,  # 使用关键词作为产业名称
                user=request.user
            )
            
            return Response({
                'code': 200,
                'message': '报告生成成功',
                'data': IndustryReportSerializer(report).data
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'报告生成失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def retrieve(self, request, *args, **kwargs):
        """获取单个报告"""
        try:
            instance = self.get_object()
            # 检查权限：只有超级用户或报告所有者可以查看
            if not request.user.is_superuser and instance.user != request.user:
                return Response({
                    'code': 403,
                    'message': '无权限查看此报告'
                }, status=status.HTTP_403_FORBIDDEN)
            
            serializer = self.get_serializer(instance)
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': serializer.data
            })
        except Report.DoesNotExist:
            return Response({
                'code': 404,
                'message': '报告不存在'
            }, status=status.HTTP_404_NOT_FOUND)

    def destroy(self, request, *args, **kwargs):
        """删除报告"""
        try:
            instance = self.get_object()
            # 检查权限：只有超级用户或报告所有者可以删除
            if not request.user.is_superuser and instance.user != request.user:
                return Response({
                    'code': 403,
                    'message': '无权限删除此报告'
                }, status=status.HTTP_403_FORBIDDEN)
            
            self.perform_destroy(instance)
            return Response({
                'code': 200,
                'message': '删除成功'
            })
        except Report.DoesNotExist:
            return Response({
                'code': 404,
                'message': '报告不存在'
            }, status=status.HTTP_404_NOT_FOUND)

    def get_object(self):
        """重写获取对象方法，添加权限过滤"""
        obj = super().get_object()
        if obj.workflow_name != 2:  # 确保是产业报告
            raise Report.DoesNotExist
        return obj

    @action(detail=True, methods=['get'])
    def download(self, request, pk=None):
        """下载报告纯文本"""
        try:
            report = self.get_object()
            
            # 检查权限
            if not request.user.is_superuser and report.user != request.user:
                return Response({
                    'code': 403,
                    'message': '无权限下载此报告'
                }, status=status.HTTP_403_FORBIDDEN)

            # 准备文件名
            filename = f"{report.title}.txt"
            
            # 创建响应（内容已经是处理过的格式）
            response = HttpResponse(report.content, content_type='text/plain; charset=utf-8')
            response['Content-Disposition'] = f'attachment; filename="{filename}"'
            
            return response
            
        except Report.DoesNotExist:
            return Response({
                'code': 404,
                'message': '报告不存在'
            }, status=status.HTTP_404_NOT_FOUND)

    def update(self, request, *args, **kwargs):
        """更新报告"""
        try:
            instance = self.get_object()
            # 检查权限：只有超级用户或报告所有者可以修改
            if not request.user.is_superuser and instance.user != request.user:
                return Response({
                    'code': 403,
                    'message': '无权限修改此报告'
                }, status=status.HTTP_403_FORBIDDEN)

            # 部分更新
            serializer = self.get_serializer(
                instance, 
                data=request.data, 
                partial=True
            )
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)

            return Response({
                'code': 200,
                'message': '更新成功',
                'data': IndustryReportSerializer(instance).data
            })
        except Report.DoesNotExist:
            return Response({
                'code': 404,
                'message': '报告不存在'
            }, status=status.HTTP_404_NOT_FOUND)
